import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import {
  DriverSelect,
  GroupTreeSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import request from '@/utils/request';
import {
  DeleteOutlined,
  DownloadOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { Button, message, Modal, Space } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import Detail from './components/Detail';
import Save from './components/Save';

const Index = (props) => {
  const { source = 'default' } = props;
  const crudRef = useRef();
  const [mode, setMode] = useState('list');
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [record, setRecord] = useState();
  const [dataSource, setDataSource] = useState([]);
  const getList = async (params) => {
    const res = await request({
      url: '/datas/etc/price/list',
      method: 'GET',
      custom: true,
      params: params,
    });
    setDataSource(res?.data || []);
    return {
      total: res?.total,
      data: res?.data || [],
      // data: [{}],
    };
  };

  const deleteRow = (id) => {
    const ids = id ? [id] : selectedKeys;
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/etc/price/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload()?.then?.((res) => {
          setMode('list');
        });
        setSelectedKeys([]);
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 220,
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
    },
    {
      title: '司机',
      dataIndex: 'realname',
      width: 220,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '金额（元）',
      dataIndex: 'price',
      width: 120,
    },
    {
      title: '开始时间',
      dataIndex: 'beginTime',
      width: 200,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      width: 200,
    },
    {
      title: '进入站点',
      dataIndex: 'beginStation',
      width: 150,
    },
    {
      title: '离开站点',
      dataIndex: 'endStation',
      width: 150,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 150,
    },
    {
      title: '系统时间',
      dataIndex: 'time',
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'etcPriceId',
      width: 150,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <Space>
            {source !== 'unbound' && (
              <>
                <a
                  onClick={() => {
                    setRecord(record);
                    setMode('edit');
                  }}
                >
                  编辑
                </a>
                <a
                  onClick={() => {
                    deleteRow(record.etcPriceId);
                  }}
                >
                  删除
                </a>
              </>
            )}
            <a
              onClick={() => {
                setRecord(record);
                setMode('detail');
              }}
            >
              详情
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '组织',
      name: 'groupId',
      width: 220,
      children: <GroupTreeSelect placeholder="请选择组织" />,
    },
    {
      label: '车牌号',
      name: 'vehicleId',
      width: 120,
      children: <VehicleSelect placeholder="请选择车牌号" />,
    },
    {
      label: '司机',
      name: 'driverId',
      width: 150,
      children: <DriverSelect placeholder="请选择司机" />,
    },
    {
      label: '开始时间',
      name: 'fromTime',
      formItemProps: {
        required: true,
      },
      children: (
        <DatePicker
          allowClear={false}
          placeholder="请选择开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          showTime
        />
      ),
    },
    {
      label: '结束时间',
      name: 'toTime',
      children: (
        <DatePicker
          allowClear={false}
          placeholder="请选择结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          showTime
        />
      ),
      formItemProps: {
        required: true,
      },
    },
  ];

  const handleExport = async () => {
    const params = crudRef.current?.getParams();
    const res = await request({
      url: '/datas/etc/price/export/list',
      method: 'GET',
      params,
    });
    window.open(res);
  };

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="etcPriceId"
        queryFormProps={{
          labelCol: 7,
          initialValues: {
            fromTime: dayjs().subtract(30, 'day').startOf('day'),
            toTime: dayjs().endOf('day'),
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        transformParams={(params) => {
          return {
            ...params,
            fromTime: params?.fromTime?.format('YYYY-MM-DD HH:mm:ss'),
            toTime: params?.toTime?.format('YYYY-MM-DD HH:mm:ss'),
          };
        }}
        toolbar={
          <>
            {source === 'default' && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setMode('add')}
              >
                新增
              </Button>
            )}
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedKeys.length === 0}
              onClick={() => deleteRow()}
            >
              批量删除
            </Button>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
          </>
        }
        tableProps={{
          pagination: {
            defaultPageSize: 200,
          },
          rowSelection: {
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys) => {
              setSelectedKeys(selectedRowKeys);
            },
          },
          // rowClassName: (record) => {
          //   return record.state !== 0 ? 'highlight-row' : '';
          // },
        }}
        // toolbar={
        //   <>
        //     <Button
        //       type="primary"
        //       icon={<DownloadOutlined />}
        //       onClick={handleExport}
        //     >
        //       导出
        //     </Button>
        //   </>
        // }
      />
      {(mode === 'edit' || mode === 'add') && (
        <Save
          source={source}
          // open={mode === 'edit' || mode === 'add'}
          record={record}
          onCancel={() => {
            setRecord(null);
            // setRecordIndex();
            setMode('list');
          }}
          onOk={(goOn) => {
            // setRecord();
            if (goOn) {
              setRecordIndex((_val) => {
                if (_val + 1 > dataSource.length) {
                  setMode('list');
                  return;
                }
                return _val + 1;
              });
            } else {
              setRecord(null);
              setMode('list');
            }
            crudRef.current?.reload();
          }}
        />
      )}

      <Detail
        source={source}
        open={mode === 'detail'}
        record={record}
        onCancel={() => {
          setRecord(null);
          setMode('list');
        }}
      />
    </>
  );
};

export default Index;
